import { Injectable } from '@angular/core';
import { HttpRequest } from '@angular/common/http';

import { BaseInterceptor } from './base.interceptor';
import { AuthConfig } from '../../config/auth.config';
import { IToken } from '../auth.interface';
import { TokenService } from './token.service';
import { check } from './utils';

/**
 * 请求拦截器
 */
@Injectable()
export class TokenInterceptor extends BaseInterceptor {

  isAuth(options: AuthConfig): boolean {
    this.model = this.injector.get(TokenService).get() as IToken;
    return check(this.model);
  }

  setReq(req: HttpRequest<any>, options: AuthConfig): HttpRequest<any> {
    const token = options.token_send_template.replace(
      /\$\{([\w]+)\}/g,
      (_: string, g) => this.model[g],
    );
    switch (options.token_send_place) {
      case 'header':
        const obj = {};
        obj[options.token_send_key] = token;
        req = req.clone({
          setHeaders: obj,
        });
        break;
      case 'body':
        const body = req.body || {};
        body[options.token_send_key] = token;
        req = req.clone({
          body: body,
        });
        break;
      case 'url':
        req = req.clone({
          params: req.params.append(options.token_send_key, token),
        });
        break;
      case 'cookie':
        req = req.clone({
          withCredentials: true
        });
        break;
      default:
        break;
    }
    return req;
  }

}
